// goods-detail.js
var WxParse = require('../../wxParse/wxParse.js');
var timer = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img_height:'',
    current:'0',
    active_text:1,
    gift:5,
    showGift:false, //是否显示进店有礼
    goods:{
      img:[
        'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
        'http://img2.imgtn.bdimg.com/it/u=3519338731,3616151357&fm=26&gp=0.jpg',
        'http://img0.imgtn.bdimg.com/it/u=1390480550,1417457842&fm=26&gp=0.jpg'
      ],
      name:'法国·AOP干红葡萄酒 Frank推荐 44年老藤 口感纯正  750ml',
      price:'280',
      discount:'249',
      seckill:'98',
      seckill_time: '2017-7-31 17:32',
      express:'150',
      express_free:'500',
      sale:'8',
      comment:new Array(232)
    },
    seckill_time_str:'',
    comment:[
      {
        name:'社会我凯哥',
        ava:'http://img3.imgtn.bdimg.com/it/u=3847576794,2197016365&fm=26&gp=0.jpg',
        content:'法国·AOP干红葡萄酒，口感真的很纯正，价格也不贵，虽然不敢说自己是个会品酒的人，但是我在欧洲也生活了一段时间，法国十大酒庄的酒基本都喝过',
        collection:'99',
        good:'88',
        img:[
          'http://img5.imgtn.bdimg.com/it/u=2717108253,1394641316&fm=26&gp=0.jpg',
          'http://img0.imgtn.bdimg.com/it/u=1390480550,1417457842&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
        ]
      },
      {
        name: '社会我凯哥',
        ava: 'http://img3.imgtn.bdimg.com/it/u=3847576794,2197016365&fm=26&gp=0.jpg',
        content: '法国·AOP干红葡萄酒，口感真的很纯正，价格也不贵，虽然不敢说自己是个会品酒的人，但是我在欧洲也生活了一段时间，法国十大酒庄的酒基本都喝过',
        collection: '99',
        good: '88',
        img: [
          'http://img5.imgtn.bdimg.com/it/u=2717108253,1394641316&fm=26&gp=0.jpg',
          'http://img0.imgtn.bdimg.com/it/u=1390480550,1417457842&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
        ]
      },
      {
        name: '社会我凯哥',
        ava: 'http://img3.imgtn.bdimg.com/it/u=3847576794,2197016365&fm=26&gp=0.jpg',
        content: '法国·AOP干红葡萄酒，口感真的很纯正，价格也不贵，虽然不敢说自己是个会品酒的人，但是我在欧洲也生活了一段时间，法国十大酒庄的酒基本都喝过',
        collection: '99',
        good: '88',
        img: [
          'http://img5.imgtn.bdimg.com/it/u=2717108253,1394641316&fm=26&gp=0.jpg',
          'http://img0.imgtn.bdimg.com/it/u=1390480550,1417457842&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
          'http://img2.imgtn.bdimg.com/it/u=4190689918,1174447526&fm=26&gp=0.jpg',
        ]
      }
    ]
  },
  reset(e){
    wx.createSelectorQuery().select('.img' + e.detail.current).boundingClientRect().exec( res => {
      this.setData({
        img_height: res[0].height
      })
    })
    this.setData({
      current: e.detail.current
    })
  },

  click(e){
    this.setData({
      active_text: e.target.dataset.name
    })
  },
  seckill_time(start_time,end_time,callback){
    
    if (new Date().valueOf() >= new Date(end_time).valueOf()){
      let data = this.data.data
      data.product_info.is_seckill = 1
      this.setData({data})
      return
    }
    else if (new Date().valueOf() >= new Date(start_time).valueOf() && new Date().valueOf() < new Date(end_time).valueOf()){
      var time = end_time
      this.setData({
        seckill_type: 'end'
      }) 
    }
    else if (new Date().valueOf() < new Date(start_time).valueOf()){
      var time = start_time
      this.setData({
        seckill_type: 'start'
      })     
    } 
    var that = this

    clearInterval(timer)
    timer = setInterval( ()=>{
      // let t = (new Date(time) - new Date())/24/3600000;
      // let time = 150888888888;

      // let t = (new Date(time).valueOf() - new Date().valueOf()) / 24 / 3600000;
      // console.log("判断t值", t)
      // let day = Math.floor(t)   
      // let hour = Math.floor(t * 24)
      // let min = Math.floor((t *24 - hour) * 60)
      // let s = Math.floor(((t * 24 - hour) * 60- min)*60)
      // console.log("判断s值",s)

      let t = (new Date(time).valueOf() - new Date().valueOf());
      // console.log("判断t值", t)
      let day = parseInt(t / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
      let hour = parseInt(t / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
      let min = parseInt(t / 1000 / 60 % 60, 10);//计算剩余的分钟 
      let s = parseInt(t / 1000 % 60, 10);//计算剩余的秒数 
      // console.log("判断s值", s)

      let str = Number(day) + '天' + Number(hour) + '小时' + Number(min) + '分' + Number(s) + '秒'
      // console.log(str)
      callback(str);
      if (str == '0天0小时0分0秒') {
        console.log('change')
        that.setData({
          seckill_type: 'end'
        })
      }
      console.log('seckill_type', that.data.seckill_type)
      // if (that.data.seckill_type =='end' && Number(s)==0){
      if (that.data.seckill_type == 'end' && str == '0天0小时0分0秒') {
        clearInterval(timer);
        that.onLoad(that.data.options);
      }
    },1000)
  },
  getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if(month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + " " + date.getHours() + seperator2 + date.getMinutes()
    + seperator2 + date.getSeconds();
    return currentdate;
  },
  closeMsk(e){
    console.log(e.target.dataset.name)
    if (e.target.dataset.name == 'msk'){
      this.setData({
        showGift : false
      })
    }
  },
  getData(id, images){
    wx.showLoading({
      title: '正在加载...',
      mask: true
    })
    let baseUrl = getApp().globalData.baseUrl,
        access_token = getApp().globalData.access_token,
        self = this
    wx.request({
      url: baseUrl + '/Index/form',
      method: 'get',
      // data: { access_token, id, images, ms_end_time},
      data: { access_token, id},
      success: data => {
        wx.hideLoading()
        if(data.data.code == 200){
          // 初始化第一张轮播图的高度
          wx.getSystemInfo({
            success: res => {
              wx.getImageInfo({
                src: data.data.data.product_info.images.photo[0].url,
                success: res2 => {
                  self.setData({
                    img_height: res.windowWidth / res2.width * res2.height
                  })
                }
              })
            }
          })
          // let ms_end_time=data.data.data.product_info.ms_end_time
          self.setData({
            data: data.data.data
          })
         

          //商品详情的富文本信息
          //console.log('222', self.data.data)
          var article = self.data.data.product_info.item;
          WxParse.wxParse('article', 'html', article, self, 5);
          console.log('ms_start_time为', data.data.data.product_info.ms_start_time)
          console.log('ms_end_time为', data.data.data.product_info.ms_end_time)
          console.log('ms_end_time的类型为',typeof data.data.data.product_info.ms_end_time)
          self.seckill_time(data.data.data.product_info.ms_start_time,data.data.data.product_info.ms_end_time, str => {
            self.setData({
              seckill_time_str: str
            })
          })
          // 进店有礼
          console.log(data.data.data)
          let card_length = 0
          for (let i in data.data.data.card) {
            card_length++
          }
          console.log(card_length)
          if (card_length > 0) {
            self.setData({
              showGift: true
            })
          }
        }
      }
    })
  },
  // 加入购物车
  add_cart(){
    wx.showLoading({
      title: '正在添加...',
      mask: true
    })
    let baseUrl = getApp().globalData.baseUrl,
      access_token = getApp().globalData.access_token,
      product_id = this.data.data.product_info.id,
      header = getApp().globalData.header,
      // price ,
      // num = this.data.data.product_info.num,
      // is_seckill = this.data.data.product_info.is_seckill,
      // coupon_id = this.data.hasOwnProperty('coupon') && typeof this.data.data.coupon.unused != null ? this.data.data.coupon.unused[this.data.coupon].coupon_id : '',
      self = this

    // if (parseInt(this.data.data.product_info.is_seckill) == 2 && new Date(this.data.data.product_info.ms_start_time).valueOf() < new Date().valueOf()) {
    //   price = this.data.data.product_info.seckill_price
    // } else {
    //   price = this.data.data.product_info.sell_price
    // }

    wx.request({
      url: baseUrl + '/Car/add_car',
      method: 'post',
      header,
      data: { access_token, product_id},
      success: data => {
        wx.hideLoading()
        console.log("看库存是否为零", data)
        if(data.data.code == 200){
          wx.showToast({
            title: '添加成功！',
          })
        }else{
          wx.showToast({
            title: data.data.message
          })
        }
      }
    })
  },
  // 立即购买
  buy_now(){
    wx.showLoading({
      title: '正在加载...',
      mask: true
    })
    let baseUrl = getApp().globalData.baseUrl,
      access_token = getApp().globalData.access_token,
      header = getApp().globalData.header,
      price ,
      product_id = this.data.data.product_info.id,
      num = this.data.data.product_info.num,
      is_seckill = this.data.data.product_info.is_seckill,
      coupon_id = this.data.hasOwnProperty('coupon') && typeof this.data.data.coupon.unused != null ? this.data.data.coupon.unused[this.data.coupon].coupon_id : '',
      self = this
    
    if (parseInt(this.data.data.product_info.is_seckill) == 2 && (new Date().valueOf() >= new Date(this.data.data.product_info.ms_start_time).valueOf() && new Date().valueOf() < new Date(this.data.data.product_info.ms_end_time).valueOf())){
      price = this.data.data.product_info.seckill_price
    } else if (parseInt(this.data.data.product_info.is_seckill) == 2 && new Date().valueOf() < new Date(this.data.data.product_info.ms_start_time).valueOf()){
      price = this.data.data.product_info.seckill_price
    }else{
      price = this.data.data.product_info.sell_price
    }
    wx.request({
      url: baseUrl + '/Order/check',
      method: 'get',
      header,
      data: { access_token, product_id, price, num, is_seckill, coupon_id},
      success: data => {
        // return console.log(data)
        wx.hideLoading()
        console.log("看库存是否为零", data.data)
        if (data.data.code == 200 && data.data.data.list[0].stock!=0) {
        // if (data.data.code == 200) {
          console.log('1')
          let that =this
          if (that.data.seckill_type == 'start'){
            console.log('1-1')
            wx.showToast({
              title: "时间未到，请耐心等待"
            })
          }else{
            wx.navigateTo({
              url: `../confirm-order/confirm-order?product_id=${product_id}&&price=${price}&&isBuyNow=${true}`
            });
          }
        } else{
          console.log('2')
          wx.showToast({
            title: "库存不足，请浏览其他商品!"
          })
        }
      }
    })
  },
  // 领取优惠券
  getCoupon() {
    wx.showLoading({
      title: '正在领取...',
      mask: true
    })
    let baseUrl = getApp().globalData.baseUrl,
      access_token = getApp().globalData.access_token,
      card_id = this.data.data.card.id,
      header = getApp().globalData.header,
      self = this

    wx.request({
      url: baseUrl + '/Card/get_coupons',
      method: 'GET',
      data: { access_token, card_id },
      success: data => {
        // console.log(data.data)
        wx.hideLoading()
        if (data.data.code == 200) {
          wx.showToast({
            title: '领取成功！'
          })
          self.setData({
            showGift: false
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      options: options
    })
    let id = options.id;
    let images = options.images;
    let ms_end_time = options.ms_end_time;
    let self = this
    self.setData({
      id: id,
      images: images,
      ms_end_time: options.ms_end_time
    })
    // this.getData(options.id, options.images, options.ms_end_time); 
    this.getData(options.id);
  },
    
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) { 
    this.reset({ detail: { current:0}}); 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    
    let  title = this.data.data.product_info.name;
    
    return {
      title: title,
    }
    console.log("分享主题：", title)
  },
})